package com.ruoyi.asset.utils;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 打印模板工具
 */
public class PrintUtil {

    /**
     * 根据参数和模板生成要打印的HTML
     *
     * @param tplName
     * @param data
     * @return 结果
     */
    public static String render(String tplName, Map<String, Object> data){
        initVelocity();

        VelocityContext velocityContext = new VelocityContext();
        for(Map.Entry<String,Object> e:data.entrySet()){
            velocityContext.put(e.getKey(), e.getValue());
        }
        velocityContext.put("date", new DateUtil());

        //渲染
        try {
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate("print/"+tplName+".html", Constants.UTF8);
            tpl.merge(velocityContext, sw);
            return sw.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 初始化vm方法
     */
    public static void initVelocity()
    {
        Properties p = new Properties();
        try
        {
            // 加载classpath目录下的vm文件
            p.setProperty("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            // 定义字符集
            p.setProperty(Velocity.INPUT_ENCODING, Constants.UTF8);
            // 初始化Velocity引擎，指定配置Properties
            Velocity.init(p);
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }
}
